{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dfsDR_omdNea"
      },
      "source": [
        "# Gemini API: Automated Invoice and Form Data Extraction with Gemini API & Pydantic\n",
        "\n",
        "This notebook demonstrates how you can convert a PDF file so that it can be read by the Gemini API.\n",
        "\n",
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Pdf_structured_outputs_on_invoices_and_forms.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cdfdb44021cd"
      },
      "source": [
        "## 1. Set up Environment and create inference Client\n",
        "\n",
        "The first task is to install the `google-genai` [Python SDK](https://googleapis.github.io/python-genai/) and obtain an API key. If you don”t have a can get one from Google AI Studio: [Get a Gemini API key](https://aistudio.google.com/app/apikey). If you are new to Google Colab checkout the [quickstart](../quickstarts/Authentication.ipynb)).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7bb370b2609a"
      },
      "outputs": [],
      "source": [
        "%pip install \"google-genai>=1\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d23fd7166d83"
      },
      "source": [
        "Once you have the SDK and API key, you can create a client and define the model you are going to use the new Gemini Flash model, which is available via [free tier](https://ai.google.dev/pricing#2_0flash) with 1,500 request per day (at 2025-02-06). "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "metadata": {
        "id": "4cf581eca5ef"
      },
      "outputs": [],
      "source": [
        "from google import genai\n",
        "from google.colab import userdata\n",
        "api_key = userdata.get(\"GOOGLE_API_KEY\") # If you are not using Colab you can set the API key directly\n",
        "\n",
        "# Create a client\n",
        "client = genai.Client(api_key=api_key)\n",
        "\n",
        "# Define the model you are going to use\n",
        "model_id =  \"gemini-2.5-flash\" # or \"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-pro\",\"gemini-3-pro-preview\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7403eae04304"
      },
      "source": [
        "*Note: If you want to use Vertex AI see [here](https://googleapis.github.io/python-genai/#create-a-client) how to create your client*"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e68aefb88671"
      },
      "source": [
        "## 2. Work with PDFs and other files\n",
        "\n",
        "Gemini models are able to process [images and videos](https://ai.google.dev/gemini-api/docs/vision?lang=python#image-input), which can used with base64 strings or using the `files`api. After uploading the file you can include the file uri in the call directly. The Python API includes a [upload](https://googleapis.github.io/python-genai/#upload) and [delete](https://googleapis.github.io/python-genai/#delete) method. \n",
        "\n",
        "For this example you have 2 PDFs samples, one basic invoice and on form with and written values. \n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "37e99d94e05b"
      },
      "outputs": [],
      "source": [
        "!wget -q -O handwriting_form.pdf https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/handwriting_form.pdf\n",
        "!wget -q -O invoice.pdf https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/invoice.pdf"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9e451e09e1e1"
      },
      "source": [
        "You can now upload the files using our client with the `upload` method. Let's try this for one of the files.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "a26a622caec8"
      },
      "outputs": [],
      "source": [
        "invoice_pdf = client.files.upload(file=\"invoice.pdf\", config={'display_name': 'invoice'})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c02e316f6b80"
      },
      "source": [
        "_Note: The File API lets you store up to 20 GB of files per project, with a per-file maximum size of 2 GB. Files are stored for 48 hours. They can be accessed in that period with your API key, but they cannot be downloaded. File uploads are available at no cost._\n",
        "\n",
        "After a file is uploaded you can check to how many tokens it got converted. This not only help us understand the context you are working with it also helps to keep track of the cost. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "268cecdab1b4"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "File: invoice equals to 821 tokens\n"
          ]
        }
      ],
      "source": [
        "file_size = client.models.count_tokens(model=model_id,contents=invoice_pdf)\n",
        "print(f'File: {invoice_pdf.display_name} equals to {file_size.total_tokens} tokens')\n",
        "# File: invoice equals to 821 tokens"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "13215cead66e"
      },
      "source": [
        "## 3. Structured outputs with Gemini 2.0 and Pydantic\n",
        "\n",
        "Structured Outputs is a feature that ensures Gemini always generate responses that adhere to a predefined format, such as JSON Schema. This means you have more control over the output and how to integrate it into our application as it is guaranteed to return a valid JSON object with the schema you define. \n",
        "\n",
        "Gemini 2.0 currenlty supports 3 dfferent types of how to define a JSON schemas:\n",
        "- A single python type, as you would use in a [typing annotation](https://docs.python.org/3/library/typing.html).\n",
        "- A Pydantic [BaseModel](https://docs.pydantic.dev/latest/concepts/models/)\n",
        "- A dict equivalent of [genai.types.Schema](https://googleapis.github.io/python-genai/genai.html#genai.types.Schema) / [Pydantic BaseModel](https://docs.pydantic.dev/latest/concepts/models/)\n",
        "\n",
        "Lets look at quick text-based example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "fcb7f5a10c3e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"age\": 0,\n",
            "  \"first_name\": \"Philipp\",\n",
            "  \"last_name\": \"Schmid\",\n",
            "  \"work_topics\": [\n",
            "    {\n",
            "      \"name\": \"AI\"\n",
            "    },\n",
            "    {\n",
            "      \"name\": \"Gemini\"\n",
            "    },\n",
            "    {\n",
            "      \"name\": \"Gemma\"\n",
            "    }\n",
            "  ]\n",
            "}\n",
            "First name is Philipp\n"
          ]
        }
      ],
      "source": [
        "from pydantic import BaseModel, Field\n",
        "\n",
        "# Define a Pydantic model\n",
        "# Use the Field class to add a description and default value to provide more context to the model\n",
        "class Topic(BaseModel):\n",
        "    name: str = Field(description=\"The name of the topic\")\n",
        "\n",
        "class Person(BaseModel):\n",
        "    first_name: str = Field(description=\"The first name of the person\")\n",
        "    last_name: str = Field(description=\"The last name of the person\")\n",
        "    age: int = Field(description=\"The age of the person, if not provided please return 0\")\n",
        "    work_topics: list[Topic] = Field(description=\"The fields of interest of the person, if not provided please return an empty list\")\n",
        "\n",
        "\n",
        "# Define the prompt\n",
        "prompt = \"Philipp Schmid is a Senior AI Developer Relations Engineer at Google DeepMind working on Gemini, Gemma with the mission to help every developer to build and benefit from AI in a responsible way.  \"\n",
        "\n",
        "# Generate a response using the Person model\n",
        "response = client.models.generate_content(model=model_id, contents=prompt, config={'response_mime_type': 'application/json', 'response_schema': Person})\n",
        "\n",
        "# print the response as a json string\n",
        "print(response.text)\n",
        "\n",
        "# sdk automatically converts the response to the pydantic model\n",
        "philipp: Person = response.parsed\n",
        "\n",
        "# access an attribute of the json response\n",
        "print(f\"First name is {philipp.first_name}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "98ba7c85f7a4"
      },
      "source": [
        "## 4. Extract Structured data from PDFs using Gemini 2.0\n",
        "\n",
        "Now, let's combine the File API and structured output to extract information from our PDFs. You can create a simple method that accepts a local file path and a pydantic model and return the structured data for us. The method will:\n",
        "\n",
        "1. Upload the file to the File API\n",
        "2. Generate a structured response using the Gemini API\n",
        "3. Convert the response to the pydantic model and return it\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "4bae48dddcf3"
      },
      "outputs": [],
      "source": [
        "def extract_structured_data(file_path: str, model: BaseModel):\n",
        "    # Upload the file to the File API\n",
        "    file = client.files.upload(file=file_path, config={'display_name': file_path.split('/')[-1].split('.')[0]})\n",
        "    # Generate a structured response using the Gemini API\n",
        "    prompt = f\"Extract the structured data from the following PDF file\"\n",
        "    response = client.models.generate_content(model=model_id, contents=[prompt, file], config={'response_mime_type': 'application/json', 'response_schema': model})\n",
        "    # Convert the response to the pydantic model and return it\n",
        "    return response.parsed"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8657cdd843fa"
      },
      "source": [
        "In our Example every PDF is a different to each other. So you want to define unique Pydantic models for each PDF to show the performance of the Gemini 2.0. If you have very similar PDFs and want to extract the same information you can use the same model for all of them. \n",
        "\n",
        "- `Invoice.pdf` : Extract the invoice number, date and all list items with description, quantity and gross worth and the total gross worth\n",
        "- `handwriting_form.pdf` : Extract the form number, plan start date and the plan liabilities beginning of the year and end of the year\n",
        "\n",
        "_Note: Using Pydantic features you can add more context to the model to make it more accurate as well as some validation to the data. Adding a comprehensive description can significantly improve the performance of the model. Libraries like [instructor](https://python.useinstructor.com/) added automatic retries based on validation errors, which can be a great help, but come at the cost of additional requests._\n",
        "\n",
        "\n",
        "### Invoice.pdf\n",
        "\n",
        "![Invoice.pdf](https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/invoice.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "e3c8f5b59da8"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "<class '__main__.Invoice'>\n",
            "Extracted Invoice: 27301261 on 10/09/2012 with total gross worth 544.46\n",
            "Item: Lilly Pulitzer dress Size 2 with quantity 5.0 and gross worth 247.5\n",
            "Item: New ERIN Erin Fertherston Straight Dress White Sequence Lining Sleeveless SZ 10 with quantity 1.0 and gross worth 65.99\n",
            "Item: Sequence dress Size Small with quantity 3.0 and gross worth 115.5\n",
            "Item: fire los angeles dress Medium with quantity 3.0 and gross worth 21.45\n",
            "Item: Eileen Fisher Women's Long Sleeve Fleece Lined Front Pockets Dress XS Gray with quantity 3.0 and gross worth 52.77\n",
            "Item: Lularoe Nicole Dress Size Small Light Solid Grey/ White Ringer Tee Trim with quantity 2.0 and gross worth 8.25\n",
            "Item: J.Crew Collection Black & White sweater Dress sz S with quantity 1.0 and gross worth 33.0\n"
          ]
        }
      ],
      "source": [
        "from pydantic import BaseModel, Field\n",
        "\n",
        "class Item(BaseModel):\n",
        "    description: str = Field(description=\"The description of the item\")\n",
        "    quantity: float = Field(description=\"The Qty of the item\")\n",
        "    gross_worth: float = Field(description=\"The gross worth of the item\")\n",
        "\n",
        "class Invoice(BaseModel):\n",
        "    \"\"\"Extract the invoice number, date and all list items with description, quantity and gross worth and the total gross worth.\"\"\"\n",
        "    invoice_number: str = Field(description=\"The invoice number e.g. 1234567890\")\n",
        "    date: str = Field(description=\"The date of the invoice e.g. 2024-01-01\")\n",
        "    items: list[Item] = Field(description=\"The list of items with description, quantity and gross worth\")\n",
        "    total_gross_worth: float = Field(description=\"The total gross worth of the invoice\")\n",
        "\n",
        "\n",
        "result = extract_structured_data(\"invoice.pdf\", Invoice)\n",
        "print(type(result))\n",
        "print(f\"Extracted Invoice: {result.invoice_number} on {result.date} with total gross worth {result.total_gross_worth}\")\n",
        "for item in result.items:\n",
        "    print(f\"Item: {item.description} with quantity {item.quantity} and gross worth {item.gross_worth}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1f34f1b9f793"
      },
      "source": [
        "Fantastic! The model did a great job extracting the information from the invoice. \n",
        "\n",
        "### handwriting_form.pdf\n",
        "\n",
        "![handwriting_form.pdf](https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/handwriting_form.jpg)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 29,
      "metadata": {
        "id": "d24349d82683"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Extracted Form Number: CA530082 with start date 02/05/2022. \n",
            "Plan liabilities beginning of the year 40000.0 and end of the year 55000.0\n"
          ]
        }
      ],
      "source": [
        "class Form(BaseModel):\n",
        "    \"\"\"Extract the form number, fiscal start date, fiscal end date, and the plan liabilities beginning of the year and end of the year.\"\"\"\n",
        "    form_number: str = Field(description=\"The Form Number\")\n",
        "    start_date: str = Field(description=\"Effective Date\")\n",
        "    beginning_of_year: float = Field(description=\"The plan liabilities beginning of the year\")\n",
        "    end_of_year: float = Field(description=\"The plan liabilities end of the year\")\n",
        "\n",
        "result = extract_structured_data(\"handwriting_form.pdf\", Form)\n",
        "\n",
        "print(f'Extracted Form Number: {result.form_number} with start date {result.start_date}. \\nPlan liabilities beginning of the year {result.beginning_of_year} and end of the year {result.end_of_year}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "db5dd4819309"
      },
      "source": [
        "## Learning more\n",
        "\n",
        "If you want to learn more about the File API, Structured Outputs and how to use it to process images, audio, and video files, check out the following resources:\n",
        "\n",
        "* Learn more about the [File API](../quickstarts/File_API.ipynb) with the quickstart.\n",
        "* Learn more about prompting with [media files](https://ai.google.dev/gemini-api/docs/file-prompting-strategies) in the docs, including the supported formats and maximum length.\n",
        "* Learn more about [Structured Outputs](https://ai.google.dev/gemini-api/docs/structured-output?lang=python) in the docs.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "55c03b7e87ba"
      },
      "source": [
        "## Property ordering with Gemini 2.0\n",
        "\n",
        "**Important:** Gemini 2.0 models require explicit ordering of keys in structured output schemas. When working with Gemini 2.0, you must define the desired property ordering as a list within the `propertyOrdering` field as part of your schema configuration.\n",
        "\n",
        "This ensures consistent and predictable ordering of properties in the JSON response, which is particularly important when the output property order matters for downstream processing."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "82bf6f49188e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"invoice_number\": \"12345\",\n",
            "  \"date\": \"2024-01-15\",\n",
            "  \"vendor\": \"Acme Corp\",\n",
            "  \"total_amount\": 1250.00\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "# Example: Specifying property ordering for Gemini 2.0\n",
        "from google import genai\n",
        "from google.genai import types\n",
        "\n",
        "# Define a schema with explicit property ordering\n",
        "invoice_schema = types.Schema(\n",
        "    type=types.Type.OBJECT,\n",
        "    properties={\n",
        "        \"invoice_number\": types.Schema(type=types.Type.STRING),\n",
        "        \"date\": types.Schema(type=types.Type.STRING),\n",
        "        \"vendor\": types.Schema(type=types.Type.STRING),\n",
        "        \"total_amount\": types.Schema(type=types.Type.NUMBER),\n",
        "    },\n",
        "    # REQUIRED for Gemini 2.0: Specify the exact order of properties, not Gemini 2.5 or newer\n",
        "    property_ordering=[\"invoice_number\", \"date\", \"vendor\", \"total_amount\"],\n",
        ")\n",
        "\n",
        "# Use the schema with generateContent\n",
        "client = genai.Client()\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=\"gemini-2.0-flash\",\n",
        "    contents=\"Extract invoice details: Invoice #12345 dated 2024-01-15 from Acme Corp for $1,250.00\",\n",
        "    config=types.GenerateContentConfig(\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=invoice_schema,\n",
        "    ),\n",
        ")\n",
        "\n",
        "print(response.text)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Pdf_structured_outputs_on_invoices_and_forms.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
